/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android app
 * Create Time: 16-2-16 下午6:43
 */

package com.lenovo.mso2o.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.lenovo.framework.base.ActionBarFragment;
import com.lenovo.framework.entity.Res;
import com.lenovo.framework.rest.NetworkObserver;
import com.lenovo.framework.util.TextHelper;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.conf.BizErrorCode;
import com.lenovo.mso2o.conf.ErrorCode;
import com.lenovo.mso2o.conf.MSConstants;
import com.lenovo.mso2o.rest.ServiceGenerator;
import com.lenovo.mso2o.rest.UserAPI;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by lit on 2015/11/16.
 */
public class ForgetpassFragment extends ActionBarFragment {
    @Bind(R.id.phone_edit)
    EditText phoneEdir;
    @Bind(R.id.number_edit)
    EditText numberEdit;
    @Bind(R.id.get_number)
    Button getNumber;
    private Subscription subscription;

    private Timer timer;
    private TimerTask task;
    private int start = 60;
    private int end = 0;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == -1) {
                getNumber.setText(start-- + "秒");
                if (start == end) {
                    timer.cancel();
                    timer.purge();
                    timer = null;
                    task.cancel();
                    task = null;
                    getNumber.setText(R.string.verify_code_resend);
                    getNumber.setEnabled(true);
                    getNumber.setClickable(true);
                    start = 60;
                }
            }

        }
    };

    @OnClick(R.id.get_number)
    void SendNumber() {
        phoneNum = phoneEdir.getText().toString();
        String msg = "test massage";
        if (!TextUtils.isEmpty(phoneNum) && TextHelper.isPhoneNum(phoneNum)) {
//            Call<Result> call = accountAPI.sendNumber("1", number, msg);
            subscription = userAPI.resetEngineerPassword(phoneNum).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .unsubscribeOn(Schedulers.io())
                    .subscribe(new NetworkObserver<Res>() {
                        @Override
                        public void onSuccess(Res res) {
                            if (res.getEcode() != 0) {
                                ErrorCode bizErrorCode = BizErrorCode.errorMap.get(res.getEcode());
                                if(bizErrorCode != null) {
                                    onFailure(bizErrorCode.getReason());
                                }else{
                                    if(res.getReason() != null && !TextUtils.isEmpty(res.getReason()))
                                        onFailure(res.getReason());
                                    else
                                        onFailure(getString(R.string.unknown_error));
                                }
                                return;
                            }
                            Toast.makeText(getActivity(), R.string.identify_code_sended, Toast.LENGTH_SHORT).show();
                            timer = new Timer();
                            task = new TimerTask() {
                                @Override
                                public void run() {
                                    handler.sendEmptyMessage(-1);
                                }
                            };
                            timer.schedule(task, 0, 1000);
                            getNumber.setEnabled(false);
                            getNumber.setClickable(false);
                        }

                        @Override
                        public void onFailure(String tip) {
                            Toast.makeText(getActivity(), tip, Toast.LENGTH_SHORT).show();
                        }
                    });
        } else {
            Toast.makeText(getActivity(), getString(R.string.input_phone_number), Toast.LENGTH_SHORT).show();
        }

    }

    private String phoneNum = "";

    @OnClick(R.id.next)
    void nextClick() {
        if (!TextUtils.isEmpty(numberEdit.getText().toString())
                && !TextUtils.isEmpty(phoneEdir.getText().toString())
                && TextHelper.isPhoneNum(phoneEdir.getText().toString())) {
            String code = numberEdit.getText().toString();
//            Call<Res> call = accountAPI.compareCode(code, phoneNum);
//            call.enqueue(new CancelableCallback<Res>() {
//                @Override
//                public void onSuccess(Res result, Response response) {
//                    if (result.getStatus() == 1) {//匹配成功，继续执行
//                        //停止倒计时
//                        if(timer != null)
//                        timer.cancel();
//                        getNumber.setText(R.string.verify_code_resend);
//                        getNumber.setEnabled(true);
//                        getNumber.setClickable(true);
//                        start = 60;
//
//                        Bundle bundle = new Bundle();
////                        bundle.putString("Code", numberEdit.getText().toString());
//                        bundle.putString("Phone", phoneNum);
//                        bundle.putString(ActionBarFragmentActivity.FRAGMENT_CLASS_NAME, ChangepassFragment.class.getName());
//                        bundle.putString(ActionBarFragmentActivity.FRAGMENT_TITLE, ChangepassFragment.class.getName());
//                        Intent intent = new Intent(getActivity(), ActionBarFragmentActivity.class);
//                        intent.putExtras(bundle);
//                        startActivity(intent);
//
//
//                    } else {
//                        int errorconde = result.getEcode();
//                        String errormsg = ErrorCode.valueOf(errorconde).getTitle();
//                        Toast.makeText(getActivity(), errormsg, Toast.LENGTH_LONG).show();
//
//                    }
//                }
//
//                @Override
//                public void onFail(String tip) {
//                    Toast.makeText(getActivity(), tip, Toast.LENGTH_LONG).show();
//                }
//            });
        } else {
            Toast.makeText(getActivity(), getString(R.string.input_auth_code), Toast.LENGTH_SHORT).show();
        }
    }

    private UserAPI userAPI;

    public static Fragment newInstance(Context context) {
        ForgetpassFragment fragment = new ForgetpassFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    public ForgetpassFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
//        调用返回不是json是string的接口，重新写的Converter(暂时用不到)
//        PlainConverter converter = new PlainConverter();
        userAPI = ServiceGenerator.createService(UserAPI.class,
                MSConstants.APIConstants.APISERVER_ADDRESS);


        return view;
    }


    @Override
    public int provideContentRes() {
        return R.layout.fragment_forgetpass;
    }

    @Override
    protected void onFragmentInVisible(Bundle savedInstanceState) {

    }

    @Override
    protected void onFragmentVisible(Bundle savedInstanceState) {

    }

    @Override
    public int getActionBarRightResourceId() {
        return 0;
    }

    @Override
    public int getActionBarRight2ResourceId() {
        return 0;
    }

    @Override
    public void onActionBarRight2Click() {

    }

    @Override
    public void onActionBarRightClick() {

    }

}
